package com.shycloud.mido.organ.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.core.exception.BusinessException;
import com.shycloud.mido.member.api.entity.BasicGoodsInfo;
import com.shycloud.mido.opter.api.entity.OptOperator;
import com.shycloud.mido.organ.api.dto.OrganizationDTO;
import com.shycloud.mido.organ.api.entity.OptOrg;
import com.shycloud.mido.organ.api.entity.Organization;
import com.shycloud.mido.organ.api.entity.TeacherDetailedEntity;
import com.shycloud.mido.organ.api.feign.RemoteMemberService;
import com.shycloud.mido.organ.api.vo.OrganizationVO;
import com.shycloud.mido.organ.mapper.OptOrgMapper;
import com.shycloud.mido.organ.mapper.OrganizationMapper;
import com.shycloud.mido.organ.mapper.TeacherDetailedMapper;
import com.shycloud.mido.organ.service.OrganizationService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * 机构相关业务 service 实现类
 *
 * @author nianhua.jiang
 * @date 2020/8/6 19:14
 */
@Service
@AllArgsConstructor
public class OrganizationServiceImpl extends ServiceImpl<OrganizationMapper, Organization> implements OrganizationService {
	
	/** 机构模块 mapper */
	private final OrganizationMapper mapper;
	/** 教师模块 mapper */
	private final TeacherDetailedMapper teacherDetailedMapper;
	/** feign 用户模块 service */
	private final RemoteMemberService remoteMemberService;
	/** 机构 代理商 绑定关系 mapper */
	private final OptOrgMapper optOrgMapper;
	
	/**
	 * 分页获取机构信息
	 *
	 * @param page 分页参数
	 * @param org  机构查询信息
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.organ.api.dto.OrganizationDTO>
	 * @author fangyan.rong
	 * @date 2020/8/7 14:58
	 */
	@Override
	public IPage<OrganizationDTO> getOrgPage(IPage<OrganizationDTO> page, OrganizationDTO org) {
		return mapper.getOrgPage(page, org);
	}
	
	/**
	 * 分页获取工作室信息
	 *
	 * @param page 分页参数
	 * @param org  查询信息
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.organ.api.dto.OrganizationDTO>
	 * @author fangyan.rong
	 * @date 2020/8/7 14:58
	 */
	@Override
	public IPage<OrganizationDTO> getStudioPage(IPage<OrganizationDTO> page, OrganizationDTO org) {
		return mapper.getStudioPage(page, org);
	}
	
	/**
	 * 修改机构欢迎语
	 *
	 * @param orgId       机构ID
	 * @param welcomeWord 欢迎语
	 * @return java.lang.Boolean
	 * @author nianhua.jiang
	 * @date 2020/8/7 14:24
	 */
	@Override
	public Boolean updateOrgName(Integer orgId, String welcomeWord) {
		
		//判断该用户是否是机构管理员
		String teacherId = remoteMemberService.getTeacherId(orgId);
		if (StrUtil.isBlank(teacherId)) {
			throw new BusinessException("获取教师身份失败，请确认您的身份");
		}
		
		//查询教师详情，看是否有权限求改机构欢迎语
		TeacherDetailedEntity orgTeacherDetailed = teacherDetailedMapper.selectById(teacherId);
		
		//教务老师才有权限更改欢迎语
		if (orgTeacherDetailed.getEducational() != 1) {
			throw new BusinessException("您还没有权限更改机构欢迎语");
		}
		//更改机构名称
		else {
			Organization organization = mapper.selectById(orgId);
			organization.setTag(welcomeWord);
			mapper.updateById(organization);
		}
		return true;
		
	}
	
	/**
	 * 编辑机构
	 *
	 * @param org 机构信息
	 * @return {@link Boolean}
	 * @author nianhua.jiang
	 * @date 2022/1/12 9:31
	 */
	@Override
	public boolean updateOrg(OrganizationVO org) {
		
		Organization organization = mapper.selectById(org.getId());
		
		//硬件/服务费 价格一致不更新，不一致进行更新
		BigDecimal jyPrice = new BigDecimal(org.getYjPrice());
		BigDecimal fwPrice = new BigDecimal(org.getFwPrice());
		
		BasicGoodsInfo goodsInfoYj = remoteMemberService.getGoodsByIdFeign(Integer.valueOf(organization.getYjGoodsId()));
		BasicGoodsInfo goodsInfoFw = remoteMemberService.getGoodsByIdFeign(Integer.valueOf(organization.getFwGoodsId()));
		
		//BigDecimal jyPriceCompare = goodsInfoYj.getGoodsPrice().divide(jyPrice, 2, BigDecimal.ROUND_HALF_UP);
		//BigDecimal fwPriceCompare = goodsInfoFw.getGoodsPrice().divide(fwPrice, 2, BigDecimal.ROUND_HALF_UP);
		
		if (jyPrice.compareTo(goodsInfoYj.getGoodsPrice()) != 0) {
			BasicGoodsInfo basicGoodsInfo = new BasicGoodsInfo();
			basicGoodsInfo.setGoodsPrice(jyPrice);
			basicGoodsInfo.setStatus("0");
			//虚拟物品
			basicGoodsInfo.setCategoryId(2);
			basicGoodsInfo.setProductId(2);
			basicGoodsInfo.setName("纠错大师押金");
			//押金金额更新,新增商品，返回商品ID，存入机构表 yjGoodsId 中
			BasicGoodsInfo goodsInfoAfter = remoteMemberService.addGoodsInfoFeign(basicGoodsInfo);
			org.setYjGoodsId(goodsInfoAfter.getId().toString());
		}
		
		if (fwPrice.compareTo(goodsInfoFw.getGoodsPrice()) != 0) {
			//服务费金额更新新增商品，返回商品ID，存入机构表 fwGoodsId 中
			BasicGoodsInfo basicGoodsInfo = new BasicGoodsInfo();
			basicGoodsInfo.setGoodsPrice(fwPrice);
			basicGoodsInfo.setStatus("0");
			//虚拟物品
			basicGoodsInfo.setCategoryId(2);
			basicGoodsInfo.setProductId(2);
			basicGoodsInfo.setName("纠错大师服务费");
			//押金金额更新,新增商品，返回商品ID，存入机构表 yjGoodsId 中
			BasicGoodsInfo goodsInfoAfter = remoteMemberService.addGoodsInfoFeign(basicGoodsInfo);
			org.setFwGoodsId(goodsInfoAfter.getId().toString());
		}
		//更新
		return mapper.updateById(org) == 1;
		
	}
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean updPreStorageCount(Integer orgId, Integer preStorageCount) {
		
		System.out.println("updPreStorageCount 接口，orgId = " + orgId + " , preStorageCount = " + preStorageCount);
		
		//增加/减少 预存剩余单数
		Organization organization = getById(orgId);
		organization.setPreStorageCount(organization.getPreStorageCount() + preStorageCount);
		//增加可分配预存未结数量
		updateById(organization);
		
		//扣除代理商对应合作商的预存单数
		List<OptOrg> optOrgs = optOrgMapper.selectList(new QueryWrapper<OptOrg>().eq("org_id", orgId));
		//为了兼容 增加/减少 预存单数
		if (preStorageCount > 0) {
			//对应代理商减少 {preStorageCount} 单预存
			if (optOrgs != null && optOrgs.size() > 0) {
				Integer optId = optOrgs.get(0).getOptId();
				//查询运营商信息
				OptOperator optOperator = optOrgMapper.getOptById(optId);
				String phone = optOperator.getPhone();
				//通过phone字段获取对应合作商的基本信息
				Integer preCount = 0;
				List<Organization> organizations = list(new QueryWrapper<Organization>().eq("phone", phone).eq("is_studio", 2));
				if (organizations != null && organizations.size() > 0) {
					Organization parentOrg = organizations.get(0);
					if (!phone.equals(organization.getPhone())) {
						Integer parentCount = parentOrg.getPreStorageCount();
						preCount = parentCount - preStorageCount;
						parentOrg.setPreStorageCount(preCount > 0 ? preCount : 0);
						updateById(parentOrg);
						//累加【预存未结】
						Integer unPreStorageCount = preCount > 0 ? preStorageCount : parentCount;
						optOrgMapper.updateOpterUnPreStorageCount(unPreStorageCount + optOperator.getUnPreStorageCount(), optOperator.getId());
					}
				}
			}
		}
		return true;
	}
	
	@Override
	public Boolean checkAndUpdPreStorageCount(Integer orgId, Integer preStorageCount) {
		
		//先判断上级代理商是否有预存单数
		List<OptOrg> optOrgs = optOrgMapper.selectList(new QueryWrapper<OptOrg>().eq("org_id", orgId));
		//对应代理商减少 {preStorageCount} 单预存
		if (optOrgs != null && optOrgs.size() > 0) {
			Integer optId = optOrgs.get(0).getOptId();
			//查询运营商信息
			OptOperator optOperator = optOrgMapper.getOptById(optId);
			String phone = optOperator.getPhone();
			//通过phone字段获取对应合作商的基本信息
			Integer preCount = 0;
			List<Organization> organizations = list(new QueryWrapper<Organization>().eq("phone", phone).eq("is_studio", 2));
			if (organizations != null && organizations.size() > 0) {
				Organization parentOrg = organizations.get(0);
				
				//若没有预存单数，则放弃
				if (parentOrg.getPreStorageCount() == 0) {
					return false;
				}
				
				//增加/减少 预存剩余单数
				Organization organization = getById(orgId);
				
				if (!phone.equals(organization.getPhone())) {
					
					organization.setPreStorageCount(organization.getPreStorageCount() + preStorageCount);
					//增加可分配预存未结数量
					updateById(organization);
					
					Integer parentCount = parentOrg.getPreStorageCount();
					preCount = parentCount - preStorageCount;
					parentOrg.setPreStorageCount(preCount > 0 ? preCount : 0);
					updateById(parentOrg);
					//累加【预存未结】
					Integer unPreStorageCount = preCount > 0 ? preStorageCount : parentCount;
					optOrgMapper.updateOpterUnPreStorageCount(unPreStorageCount + optOperator.getUnPreStorageCount(), optOperator.getId());
					return true;
				}
			}
		}
		return false;
	}
	
}
